package com.daylightrobbery.server.packet.type;


import com.daylightrobbery.server.packet.GamePacket;
import com.daylightrobbery.utils.ObjectMapperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.crypto.Data;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ShardingDataPacket implements DataPacket {

    private static final Logger log = LoggerFactory.getLogger(ShardingDataPacket.class);

    public static final int SHARDING_TYPE = 1000001;
    public static final int PACKET_LENGTH = 800;
    public long uniqueGamePacketId;
    public int id; //数据包编号
    public int type; //内部数据包类型
    public byte[] data; // 数据
    public int totalCount; // 数据包总个数

    public static List<ShardingDataPacket> splitPacket(GamePacket dataPacket){
        List<ShardingDataPacket> packets = new ArrayList<>();
        String s = ObjectMapperUtil.toJSON(dataPacket);
        //log.info("解包前的数据: " + s);
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        int shardingPacketId = 0;

        int count = 0;
        for (int i = 0; i < bytes.length; i += PACKET_LENGTH) {
            count++;
            // 右边界
            int bound = PACKET_LENGTH + i;
            if (bound > bytes.length) {
                bound = bytes.length;
            }
            byte[] data = new byte[bound - i];
            System.arraycopy(bytes, i, data, 0, bound - i);
            ShardingDataPacket packet = new ShardingDataPacket(dataPacket.getType());
            packet.setId(shardingPacketId++)
                    .setUniqueGamePacketId(dataPacket.getId())
                    .setData(data);
            packets.add(packet);
        }
        for (ShardingDataPacket packet : packets) {
            packet.setTotalCount(count);
        }
        //log.info("分组数据包的长度为: " + bytes.length);
        return packets;
    }

    public long getUniqueGamePacketId() {
        return uniqueGamePacketId;
    }

    public ShardingDataPacket setUniqueGamePacketId(long uniqueGamePacketId) {
        this.uniqueGamePacketId = uniqueGamePacketId;
        return this;
    }

    public ShardingDataPacket(int type) {
        this.type = type;
    }

    public byte[] getData() {
        return data;
    }

    public ShardingDataPacket setData(byte[] data) {
        this.data = data;
        return this;
    }

    public int getId() {
        return id;
    }

    public ShardingDataPacket setId(int id) {
        this.id = id;
        return this;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public ShardingDataPacket setTotalCount(int totalCount) {
        this.totalCount = totalCount;
        return this;
    }

    @Override
    public DataPacket process() {
        return null;
    }

    @Override
    public int getType() {
        return type;
    }
}
